package com.gxa.employment.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxa.employment.common.Result;
import com.gxa.employment.entity.dto.PageBean;
import com.gxa.employment.entity.dto.ResumeDto;
import com.gxa.employment.entity.dto.ResumeStuDto;
import com.gxa.employment.entity.dto.StuResDetailDto;
import com.gxa.employment.entity.pojo.Resume;
import com.gxa.employment.entity.pojo.StuEmpDetail;
import com.gxa.employment.entity.pojo.StuResume;
import com.gxa.employment.entity.vo.PageVo;
import com.gxa.employment.service.ResumeService;
import com.gxa.employment.service.StuEmpDetailService;
import com.gxa.employment.service.StuResumeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 学生简历表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-03-25
 */
@RestController
@RequestMapping("/resume")
public class ResumeController {
//    学生简历
//    1、需要对学生简历进行查询
//    2、审批学生简历，更新简历在对状态进行更新

    private final ResumeService resumeService;
    private final StuResumeService stuResumeService;
    private StuEmpDetailService stuEmpDetailService;

    @Value("${file.upload.dir}")
    private String uploadDir;

    public ResumeController(ResumeService resumeService, StuResumeService stuResumeService, StuEmpDetailService stuEmpDetailService) {
        this.resumeService = resumeService;
        this.stuEmpDetailService = stuEmpDetailService;
        this.stuResumeService = stuResumeService;
    }


    @PostMapping("/upload")
    public Result uploadResumes(@RequestPart List<MultipartFile> files) throws IOException {
        List<Resume> uploadedResumes = new ArrayList<>();
        for (MultipartFile file : files) {
            // 解析文件名
            Resume resume = parseFileName(file.getOriginalFilename());
            if (!resume.getResStatus()) {
                return Result.error(500, "文件名格式不正确，请使用'岗位-工作经验-姓名.扩展名'格式");
            }

            // 确保上传目录存在
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 检查文件名是否重复
            String originalFilename = file.getOriginalFilename();
            QueryWrapper<Resume> query = Wrappers.query(Resume.class).eq("res_file_name", originalFilename);
            if (resumeService.getOne(query) != null) {
                return Result.error(500, "文件名重复");
            }
            resume.setResFileName(originalFilename);

            // 生成唯一文件名
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String storedFilename = UUID.randomUUID().toString().replace("-", "") + fileExtension;

            // 保存文件
            Path filePath = uploadPath.resolve(storedFilename);
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
            }
            resume.setResPath(filePath.toString());
            uploadedResumes.add(resume);
        }
        resumeService.saveBatch(uploadedResumes);
        return Result.success();
    }

    @PostMapping("/query")
    public Result query(@RequestBody ResumeDto resumeDto) {
        System.out.println(resumeDto);
        LambdaQueryWrapper<Resume> queryWrapper = Wrappers.lambdaQuery(Resume.class);
        queryWrapper.eq(resumeDto.getResId()!=null,Resume::getResId,resumeDto.getResId())
                .like(StringUtils.isNotEmpty(resumeDto.getResFileName()),Resume::getResFileName,resumeDto.getResFileName())
                .orderByDesc(Resume::getResId);

        IPage<Resume> page = new Page<>(resumeDto.getPage(), resumeDto.getSize());
        resumeService.page(page, queryWrapper);
        List<Resume> records = page.getRecords();
        long total = page.getTotal();
        PageVo<Resume> pageVo = new PageVo<>(total, records);
        return Result.success(pageVo);
    }

    @DeleteMapping("/delete/{resId}")
    public Result delete(@PathVariable Integer resId) {
        boolean b = resumeService.removeById(resId);
        if (!b) {
            return Result.error(500, "删除失败");
        }
        return Result.success();
    }

    //    简历中心查询
    @PostMapping("/stuResume")
    public Result stuResumeQuery(@RequestBody ResumeStuDto resumeStuDto) {
        PageVo<StuResume> pageVo = stuResumeService.select(resumeStuDto);
        return Result.success(pageVo);
    }

    // 文件名解析方法
    private Resume parseFileName(String fileName) {
//        FileNameInfo info = new FileNameInfo();
        Resume resume = new Resume();
        // 去除扩展名
        String basename = fileName.replaceAll("\\.[^.]+$", "");
        String[] parts = basename.split("-");

        if (parts.length >= 4) {
            Integer stuId = Integer.valueOf(parts[0]);
            System.out.println();
            resume.setStuId(stuId);
            // 提取工作经验年限
            String experienceStr = parts[2];
            Matcher matcher = Pattern.compile("\\d").matcher(experienceStr);
            System.out.println(experienceStr);
            if (matcher.find()) {
                resume.setResExperienceYear(Integer.parseInt(matcher.group()));
            } else {
                resume.setResExperienceYear(0);
            }
            // 合并剩余部分作为姓名
            resume.setResStatus(true);
        } else {
            resume.setResStatus(false);
        }
        return resume;
    }

    //    下载接口
    @PostMapping("/queryStuResDetail")
    public Result queryStuResDetail(@RequestBody StuResDetailDto stuResDetailDto){
    //根据条件筛查信息
        LambdaQueryWrapper<StuEmpDetail> queryWrapper = Wrappers.lambdaQuery(StuEmpDetail.class);
        queryWrapper.like(StringUtils.isNotEmpty(stuResDetailDto.getStuName()),StuEmpDetail::getStuName,stuResDetailDto.getStuName())
                .like(StringUtils.isNotEmpty(stuResDetailDto.getStuMajor()),StuEmpDetail::getStuMajor,stuResDetailDto.getStuMajor())
                .like(StringUtils.isNotEmpty(stuResDetailDto.getClazzName()),StuEmpDetail::getClazzName,stuResDetailDto.getClazzName());
//        分页操作
        IPage<StuEmpDetail> page = new Page(stuResDetailDto.getPage(), stuResDetailDto.getSize());
        stuEmpDetailService.page(page, queryWrapper);
        List<StuEmpDetail> records = page.getRecords();
        long total = page.getTotal();
        PageVo<StuEmpDetail> pageVo = new PageVo( total,records);
        return Result.success(pageVo);
    }

}
